/**
 * Created by Administrator on 2015/7/3.
 */
function UtouuAjaxUploader(option){
    var self=this;
    var xhr;
    self.isLoading=false;
    var fd;
    var opt={
        url:option.url || "",
        method:"post",
        fileName:option.fileName || "file",
        load:function(evt){
            var message = evt.target.responseText;
            console.log("responseText:"+evt.target.responseText);
            option.load && option.load(eval("("+message+")"));
            self.isLoading=false;
        },
        loadstart:function(evt){
        	self.isLoading=true;
            option.loadstart && option.loadstart(evt);
        },
        loadEnd:function(evt){
            self.isLoading=false;
            option.loadEnd && option.loadEnd(evt);

        },
        progress:function(evt){
            if (evt.lengthComputable) {
                var percentComplete = Math.round(evt.loaded * 100 / evt.total);
                option.progress && option.progress(percentComplete,evt.total);
            }else {
                option.progress && option.progress(0,0);
            }
        },
        error:function(evt){
            option.error && option.error(evt);
        },
        abort:function(evt){
            option.abort && option.abort(evt);
        }
    };

    self.cancelUpdate=function(){
        xhr.abort();
    };

    var getXHR=function(){
        var xhr=new XMLHttpRequest();
        xhr.upload.addEventListener("progress",opt.progress,false);
        xhr.addEventListener("load",opt.load,false);
        xhr.addEventListener("loadstart",opt.loadstart,false);
        xhr.addEventListener("loadEnd",opt.loadEnd,false);
        xhr.addEventListener("error",opt.error,false);
        xhr.addEventListener("abort",opt.abort,false);
        return xhr;
    };

    xhr=getXHR();

    self.setFile=function(file){
        if(file){
            fd=new FormData();
            fd.append(opt.fileName,file)
        }else{
            fd=undefined;
        }
    };

    self.send=function(){
        if(!self.isLoading && fd){
            xhr.open(opt.method,opt.url);
            xhr.send(fd);
        }
    };
    return self;
}